//
//  ViewController.m
//  VoiceRecognize
//
//  Created by Khanh Nguyen on 28/11/13.
//  Copyright (c) 2013 Khanh Nguyen. All rights reserved.
//

#define COUNTER_RESET_APP   45

const unsigned char SpeechKitApplicationKey[] = {0x7b, 0x35, 0x5a, 0xc3, 0xec, 0x94, 0x1b, 0x83, 0xe6, 0x4f, 0x1f, 0x1d, 0xd0, 0x74, 0x36, 0xf3, 0xc8, 0xe7, 0x67, 0xb3, 0xc3, 0x8e, 0x6c, 0xb5, 0x97, 0x81, 0x37, 0xb6, 0xf9, 0x29, 0x01, 0x74, 0x5e, 0x5b, 0x37, 0x4b, 0xef, 0x52, 0xce, 0xd5, 0xa1, 0xee, 0xf2, 0x72, 0x62, 0x28, 0x65, 0x2a, 0x0f, 0xcc, 0xdd, 0xd3, 0x5b, 0x49, 0x88, 0xf2, 0xca, 0xc0, 0xa8, 0xc3, 0xe9, 0xa9, 0x38, 0x47};

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController







-(void)recordButtonPress:(id)sender
{
    if (transactionState == TS_RECORDING) {
        [voiceSearch stopRecording];
    }
    else if (transactionState == TS_IDLE) {
        SKEndOfSpeechDetection detectionType;
        NSString* recoType;
        NSString* langType;
        
        transactionState = TS_INITIAL;
        
        /* 'Search' is selected */
        detectionType = SKShortEndOfSpeechDetection; /* Searches tend to be short utterances free of pauses. */
        recoType = SKSearchRecognizerType; /* Optimize recognition performance for search text. */
        langType = @"en_US";//en_GB,en_US
        
//        NSLog(@"Recognizing type:'%@' Language Code: '%@' using end-of-speech detection:%d.", recoType, langType, detectionType);
        
        if (voiceSearch) [voiceSearch release];
		
        voiceSearch = [[SKRecognizer alloc] initWithType:recoType
                                               detection:detectionType
                                                language:langType
                                                delegate:self];
    }

}
#pragma mark -
#pragma mark SKRecognizerDelegate methods

- (void)recognizerDidBeginRecording:(SKRecognizer *)recognizer
{
    NSLog(@"Recording started.");
    
    transactionState = TS_RECORDING;
    [self.btnRecord setTitle:@"Recording..." forState:UIControlStateNormal];
//    [self performSelector:@selector(updateVUMeter) withObject:nil afterDelay:0.05];
}

- (void)recognizerDidFinishRecording:(SKRecognizer *)recognizer
{
    NSLog(@"Recording finished.");
    
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateVUMeter) object:nil];
//    [self setVUMeterWidth:0.];
    transactionState = TS_PROCESSING;
    [_btnRecord setTitle:@"Processing..." forState:UIControlStateNormal];
}

- (void)recognizer:(SKRecognizer *)recognizer didFinishWithResults:(SKRecognition *)results
{
    NSLog(@"Got results.");
    NSLog(@"Session id [%@].", [SpeechKit sessionID]); // for debugging purpose: printing out the speechkit session id
    
    long numOfResults = [results.results count];
    
    transactionState = TS_IDLE;
    [_btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    
    if (numOfResults > 0)
        _labelResult.text = [results firstResult];
    
	if (numOfResults > 1)
//		alternativesDisplay.text = [[results.results subarrayWithRange:NSMakeRange(1, numOfResults-1)] componentsJoinedByString:@"\n"];
    
    if (results.suggestion) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Suggestion"
                                                        message:results.suggestion
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    
	[voiceSearch release];
	voiceSearch = nil;
}

- (void)recognizer:(SKRecognizer *)recognizer didFinishWithError:(NSError *)error suggestion:(NSString *)suggestion
{
    NSLog(@"Got error.");
    NSLog(@"Session id [%@].", [SpeechKit sessionID]); // for debugging purpose: printing out the speechkit session id
    
    transactionState = TS_IDLE;
    [_btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                    message:[error localizedDescription]
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    if (suggestion) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Suggestion"
                                                        message:suggestion
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    
	[voiceSearch release];
	voiceSearch = nil;
}

#pragma mark -- Mark

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSString *appId = @"NMDPPRODUCTION_S60_Test_20131126152353";
    NSString *hostUrl = @"baf.nmdp.nuancemobility.net";
//    NSNumber *count = [[NSUserDefaults standardUserDefaults] objectForKey:@"counter"];
//    if (!count) {
//        count = [NSNumber numberWithInt:1];
//    }else {
//        NSInteger countValue = [count integerValue];
//        if (countValue > COUNTER_RESET_APP) {
//            appId = [appId stringByReplacingOccurrencesOfString:@"_S60" withString:@"013"];
//            hostUrl = [hostUrl stringByReplacingOccurrencesOfString:@"emo" withString:@"url"];
//        }else{
//            countValue ++;
//            count = [NSNumber numberWithInteger:countValue];
//            [[NSUserDefaults standardUserDefaults] setObject:count forKey:@"counter"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
//    }
    
    [SpeechKit setupWithID:appId host:hostUrl port:443 useSSL:NO delegate:self];
	// Set earcons to play
	SKEarcon* earconStart	= [SKEarcon earconWithName:@"earcon_listening.wav"];
	SKEarcon* earconStop	= [SKEarcon earconWithName:@"earcon_done_listening.wav"];
	SKEarcon* earconCancel	= [SKEarcon earconWithName:@"earcon_cancel.wav"];
	
	[SpeechKit setEarcon:earconStart forType:SKStartRecordingEarconType];
	[SpeechKit setEarcon:earconStop forType:SKStopRecordingEarconType];
	[SpeechKit setEarcon:earconCancel forType:SKCancelRecordingEarconType];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
